package com.cxy.filter;

import com.alibaba.fastjson.JSONObject;
import com.cxy.pojo.Result;
import com.cxy.utils.JwtUtils;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //获取请求
        String url = httpServletRequest.getRequestURI();
        log.info("获取请求url:{}",url);
        //判断请求是否是login
        if(url.contains("login")){
            log.info("请求为登录请求，放行");
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //获取请求头，判断请求头中是否有token
        String jwt = httpServletRequest.getHeader("token");
        if(!StringUtils.hasLength(jwt)){
            //利用fastJson来将错误结果返回,利用响应对象的getWriter将结果响应给浏览器
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            httpServletResponse.getWriter().write(s);
            return;
        }
        //解析JWT
        try {
            jwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析令牌出现错误，返回未登录错误信息");
            Result notLogin = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(notLogin);
            httpServletResponse.getWriter().write(s);
            return;
        }
        //放行
        log.info("校验成功");
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
